package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.examine.PaperActivity;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.StudyEntity;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

/**
 * Created by 390849 on 2017/9/1.
 */

public class NewStudentDetailActivity extends ParentActivity{
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.rightScroll = false;
        setContentView(R.layout.activity_study_detail);
        initSkinLayout();

        initMessageContentWebView();

        initTitleButtonBar();
        initWindow();
    }

    final Handler handler = new Handler(){

    };

    private void initMessageContentWebView() {
        webView = (WebView) findViewById(R.id.wv_msg_contents);
        webView.setBackgroundColor(0); // 设置背景色
    }

    private void initTitleButtonBar() {
        final TextView titleTv = (TextView) findViewById(R.id.tv_title);
        titleTv.setText(getString(R.string.train_learning_materials));

        final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
        backBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWindow() {
        Intent intent = getIntent();
        final StudyEntity entity = (StudyEntity) intent
                .getSerializableExtra(HctConstants.ON_ACTIVITY_KEY_STUDY_ENTITY);

        final Handler handler = new Handler(){
            public void dispatchMessage(Message msg) {
                switch (msg.what){
                    case HctConstants.STATUS_FAILD:

                        break;
                    case HctConstants.STATUS_SUCCESS:

                        break;
                }
            }


        };

        new Thread() {
            public void run() {
                HctController controller = new HctController(
                        NewStudentDetailActivity.this);
                try {
                    HctResult hctResult = controller
                            .addClickRecord(entity.bookName, LoginResultStoreUtil.get(NewStudentDetailActivity.this).personId);
                    handler.sendMessage(handler.obtainMessage(
                            HctConstants.STATUS_SUCCESS, hctResult));
                } catch (Exception e) {
                    handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
                    e.printStackTrace();
                }
            };
        }.start();
        renderMessageTitle(entity);
        initMessageContentById(entity.id);
    }

    private void renderMessageTitle(StudyEntity entity) {
        final TextView msgTitleTv = (TextView) findViewById(R.id.tv_msg_title);
        final TextView dateTv = (TextView) findViewById(R.id.tv_date);
        msgTitleTv.setText(entity.title);
        dateTv.setText(entity.date);
    }

    private void initMessageContentById(final String id) {
        final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
        final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);
        final Button reloadBtn = (Button) findViewById(R.id.btn_default_reload);

        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        loadLyt.setVisibility(View.GONE);
                        reloadLyt.setVisibility(View.GONE);

                        hctResult = (HctResult) msg.obj;

                        StudyEntity entity = (StudyEntity) hctResult.data;

                        // renderMessageContent(entity);
                        renderMessageContentUseWebView(entity);
                        renderStudyExtra(entity);
                        break;

                    case HctConstants.STATUS_FAILD:
                        loadLyt.setVisibility(View.GONE);
                        reloadLyt.setVisibility(View.VISIBLE);
                        reloadBtn.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                initMessageContentById(id);
                            }
                        });
                        break;
                }
            }

            /**
             * 根据资料详情初始化关联的试题及视频
             *
             * @param
             *            entity
             */
            private void renderStudyExtra(final StudyEntity entity) {
                if (entity == null) {
                    return;
                }
                if (!TextUtils.isEmpty(entity.videoId)) {// 无关联视频
                    findViewById(R.id.lyt_study_video).setVisibility(
                            View.VISIBLE);
                    final TextView tvVideo = (TextView) findViewById(R.id.study_video);
                    tvVideo.setText("   " + entity.videoName);
                    findViewById(R.id.lyt_study_video).setOnClickListener(
                            new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {// 跳转到视频
                                    // videoId videoName
                                    Intent intent = new Intent(
                                            NewStudentDetailActivity.this,
                                            VideoPartsActivity.class);
                                    intent.putExtra("videoId", entity.videoId);
                                    intent.putExtra("videoName",
                                            entity.videoName);
                                    startActivity(intent);
                                }
                            });

                }

                if (!TextUtils.isEmpty(entity.examId)) {// 关联试卷
                    findViewById(R.id.lyt_study_examine).setVisibility(
                            View.VISIBLE);
                    final TextView tvExam = (TextView) findViewById(R.id.study_exam);
                    tvExam.setText("   " + entity.examName);
                    findViewById(R.id.lyt_study_examine).setOnClickListener(
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {// 跳转到试卷
                                    Intent intent = new Intent(
                                            NewStudentDetailActivity.this,
                                            PaperActivity.class);
                                    intent.putExtra(
                                            HctConstants.ON_ACTIVITY_KEY_PAPER_ID,
                                            entity.examId);
                                    startActivity(intent);
                                }
                            });

                }

                if (!TextUtils.isEmpty(entity.bookId)) {// 打开资料
                    DbController dbController = new DbController(
                            NewStudentDetailActivity.this);

                    final BookListEntity.BookEntity bookEntity = dbController
                            .getBookEntity(entity.bookId);
                    if (dbController.isExists(bookEntity)) {
                        findViewById(R.id.lyt_study_book).setVisibility(
                                View.VISIBLE);
                        final TextView tvExam = (TextView) findViewById(R.id.study_book);
                        tvExam.setText("   " + bookEntity.displayName);
                        findViewById(R.id.lyt_study_book).setOnClickListener(
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {// 跳转到资料
                                        EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
                                        try {
                                            catalogUtil
                                                    .startEntryCatalogActivity(
                                                            NewStudentDetailActivity.this,
                                                            bookEntity, true);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }
                }
            }

            @SuppressLint("JavascriptInterface")
            private void renderMessageContentUseWebView(final StudyEntity entity) {

                // webView.setBackgroundColor(0); // 设置背景色
                // webView.getBackground().setAlpha(0); // 设置填充透明度 范围：0-255
                // 取消滚动条
                webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
                webView.setWebViewClient(mWebViewClient);

                webView.requestFocus(View.FOCUS_DOWN);
                webView.getSettings().setBlockNetworkImage(false);
                webView.getSettings().setSupportZoom(true);
                webView.getSettings().setDefaultTextEncodingName("UTF-8");
                webView.getSettings().setBuiltInZoomControls(true);

                webView.getSettings().setJavaScriptEnabled(true);
                webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(
                        true);
                // webView.getSettings().setPluginsEnabled(true);
                webView.getSettings()
                        .setPluginState(WebSettings.PluginState.ON);
                webView.getSettings().setSupportMultipleWindows(true);
                webView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);

                webView.getSettings().setSaveFormData(false);
                webView.getSettings().setSavePassword(false);
                webView.getSettings().setUseWideViewPort(false);
                webView.setSaveEnabled(false);
                webView.clearCache(true);

                webView.addJavascriptInterface(new NewStudentDetailActivity.JavascriptInterface(
                        NewStudentDetailActivity.this), "imagelistner");
                webView.loadDataWithBaseURL(null, entity.content, "text/html",
                        "uft-8", null);
            }

        };

        loadLyt.setVisibility(View.VISIBLE);
        reloadLyt.setVisibility(View.GONE);
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(
                            NewStudentDetailActivity.this);

                    HctResult result = controller.getStudyDetail(id);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view,
                                              HttpAuthHandler handler, String host, String realm) {
            super.onReceivedHttpAuthRequest(view, handler, host, realm);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            addImageClickListner();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // if (view != null) {
            // view.loadUrl(url);
            // }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(url);
            intent.setData(content_url);
            startActivity(intent);
            return true;
        }
    };

    // 注入js函数监听
    private void addImageClickListner() {
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，在还是执行的时候调用本地接口传递url过去
        webView.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName(\"img\"); "
                + "for(var i=0;i<objs.length;i++)  " + "{"
                + "    objs[i].onclick=function()  " + "    {  "
                + "        window.imagelistner.openImage(this.src);  "
                + "    }  " + "}" + "})()");
    }

    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        public void openImage(String img) {
            Intent intent = new Intent();
            intent.putExtra("image", img);
            intent.setClass(NewStudentDetailActivity.this,
                    ShowMegaImageActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }
}
